from django.db import models
from celery.states import PRECEDENCE
from django.contrib.auth import get_user_model


class Repository(models.Model):
    """playbook项目仓库，依托git仓库"""

    class Meta:
        db_table = "iac_repos"

    # id
    project_name = models.CharField(max_length=100)  # 必须，项目名称
    creator = models.CharField(max_length=50, null=True, blank=True)  # 项目创建者，手填，可为空
    repo_url = models.CharField(max_length=250)  # 必须，Playbook的git地址，浏览器端不用管
    created_time = models.DateTimeField(auto_now_add=True)  # insert时自动填充当前时间


# cls：被装饰的类（这里是 History）
def update_choices(cls):
    for i, v in enumerate(PRECEDENCE):
        setattr(cls, str(v), i)
    return cls


@update_choices
class History(models.Model):
    class Meta:
        db_table = 'iac_his'
        ordering = ['-start_time']  # 倒序排列

    STATUS = list(enumerate(map(lambda x: str(x), PRECEDENCE)))
    repo = models.ForeignKey(Repository, on_delete=models.PROTECT)
    task_id = models.CharField(max_length=100)
    executor = models.ForeignKey(get_user_model(), on_delete=models.PROTECT)  # 当前登录系统的用户就是执行者，记录其id
    status = models.IntegerField(choices=STATUS)
    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True)
